﻿/******************************************************/
// PostPage プレゼンテーションクラス  
/******************************************************/

using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using MAA.Business;
using MAA.Entity;

namespace MAA.Presentation.PRL.Trading
{
    public partial class PostPage : System.Web.UI.Page
    {
        private ResourceManager rm = new ResourceManager("MAA.Presentation.language", System.Reflection.Assembly.GetExecutingAssembly());
        private CultureInfo m_JapanCulture = new CultureInfo("ja-JP");
        private CultureInfo m_VietnameCulture = new CultureInfo("vi");

        private void UpdateUI()
        {
            langPostInformation.Text = rm.GetString("langPostInformation");
            langRiceType.Text = rm.GetString("langRiceType");
            langAmount.Text = rm.GetString("langAmountNotKg");
            langPostTradedAmount.Text = rm.GetString("langPostTradedAmount");
            langUnitPrice.Text = rm.GetString("langUnitPrice");
            langPostPerPrice.Text = rm.GetString("langPostPerPrice");
            langAddress.Text = rm.GetString("langAddress");
            langProvince.Text = rm.GetString("langProvince");
            langDateBuy.Text = rm.GetString("langDateBuy");
            langStatus.Text = rm.GetString("langStatus");
            btnCancelTrade.Text = rm.GetString("langCancelTransaction");
            langListOrderNow.Text = rm.GetString("langListOrderNow");
            dgvOrderBuyer.Columns[1].HeaderText = rm.GetString("langName");
            dgvOrderBuyer.Columns[7].HeaderText = rm.GetString("langAmount");
            dgvOrderBuyer.Columns[8].HeaderText = rm.GetString("langPrice");
            dgvOrderBuyer.Columns[5].HeaderText = rm.GetString("langProvince");
            dgvOrderBuyer.Columns[9].HeaderText = rm.GetString("langStatus");
            dgvOrderBuyer.Columns[2].HeaderText = rm.GetString("langPhone");
            dgvOrderBuyer.Columns[3].HeaderText = rm.GetString("langEmail");
            dgvOrderBuyer.Columns[4].HeaderText = rm.GetString("langAddress");
            btnCancelTrade.OnClientClick = "return confirm('" + rm.GetString("langConfirmCancelTransaction") + "');";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["language"] == null)
            {
                Session["language"] = "vi";
            }
            if (Session["language"].Equals("vi"))
            {
                Thread.CurrentThread.CurrentUICulture = m_VietnameCulture;
                UpdateUI();
            }
            if (Session["language"].Equals("jp"))
            {
                Thread.CurrentThread.CurrentUICulture = m_JapanCulture;
                UpdateUI();
            }
            if (IsPostBack) return;

            // Check User login
            if (Session["userID"] == null)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "popup",
                    "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(Common.MESSAGE_ERROR_NOT_LOGIN) + "');window.location='../HomePage.aspx'</script>");
            }

            long userID = Convert.ToInt64(Session["userID"]);
            long postID = Convert.ToInt64(Request.QueryString["postID"]);

            BOLTrading bolTrading = new BOLTrading();
            DataTable tblPost = new DataTable();
            DataTable tblBuyerOrder = new DataTable();

            // View detail information of post
            short status = 0;
            string messagePost = "";
            btnCancelTrade.Enabled = false;
            string lang = Session["language"].ToString();
            if (bolTrading.viewPost(lang, postID, out tblPost, out messagePost))
            {
                if (tblPost.Rows.Count > 0)
                {
                    for (int i = 0; i < tblPost.Rows.Count; ++i)
                    {
                        Session["riceID"] = Convert.ToInt32(tblPost.Rows[i]["RiceID"]);
                        lblRiceType.Text = Convert.ToString(tblPost.Rows[i]["TypeName"]);
                        lblAmount.Text = Convert.ToString(tblPost.Rows[i]["Amount"]);
                        lblTradedAmount.Text = Convert.ToString(tblPost.Rows[i]["TradedAmount"]);
                        lblPrice.Text = Convert.ToString(tblPost.Rows[i]["Price"]);
                        lblPerPrice.Text = Convert.ToString(tblPost.Rows[i]["PercentPrice"]);
                        lblAddress.Text = Convert.ToString(tblPost.Rows[i]["Address"]); ;
                        lblProvince.Text = Convert.ToString(tblPost.Rows[i]["Province"]);
                        lblCreateDate.Text = Convert.ToString(tblPost.Rows[i]["UpdateTime"]);
                        lblStatus.Text = Convert.ToString(tblPost.Rows[i]["StatusName"]);
                        lblStatus.Text = PRLCommon.ChangeLanguageStatus(lblStatus.Text);
                        status = Convert.ToInt16(tblPost.Rows[i]["Status"]);
                    }

                    // Enable/Disable button Delete post
                    if (status == 1)
                    {
                        btnCancelTrade.Enabled = true;
                    }
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messagePost) + "')</script>", false);
            }

            // View buyers & orders list of a post
            int numPendingOrder = 0;
            string messageOrderList = "";
            lblOrderListMess.Text = null;

            if (bolTrading.viewOrderList(lang, postID, out tblBuyerOrder, out messageOrderList))
            {
                dgvOrderBuyer.DataSource = tblBuyerOrder;
                dgvOrderBuyer.DataBind();

                if (tblBuyerOrder.Rows.Count > 0)
                {
                    // Enable/Disable buttons: Delete post, Accept order, Reject order
                    ImageButton btnAccept;
                    ImageButton btnReject;
                    for (int i = 0; i < tblBuyerOrder.Rows.Count; ++i)
                    {
                        btnAccept = (ImageButton)dgvOrderBuyer.Rows[i].FindControl("btnAccept");
                        btnReject = (ImageButton)dgvOrderBuyer.Rows[i].FindControl("btnReject");
                        if (Convert.ToInt16(tblBuyerOrder.Rows[i]["Status"]) == 1)
                        {
                            dgvOrderBuyer.Columns[10].Visible = true;
                            dgvOrderBuyer.Columns[11].Visible = true;
                            numPendingOrder += 1;
                            btnAccept.Visible = true;
                            btnReject.Visible = true;
                        }
                    }
                    if (numPendingOrder == 0 && status == 1)
                    {
                        btnCancelTrade.Enabled = true;
                    }
                    else
                    {
                        btnCancelTrade.Enabled = false;
                    }
                }
                else
                {
                    lblOrderListMess.Text = rm.GetString("langMESSAGE_NO_DATA_ORDER_LIST"); ;
                }
            }
            else
            {
                dgvOrderBuyer.DataSource = tblBuyerOrder;
                dgvOrderBuyer.DataBind();
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageOrderList) + "')</script>", false);
            }

            dgvOrderBuyer.Columns[0].Visible = false;
            dgvOrderBuyer.Columns[6].Visible = false;
        }

        protected void btnCancelTrade_Click(object sender, EventArgs e)
        {
            BOLTrading bolTrading = new BOLTrading();
            string message = "";

            // Show popup confirm

            // Get information of post
            Post post = getPostInfoFromScreen();

            // Thuc hien delete post

            // If thuc hien success
            if (bolTrading.cancelPost("vi",post, out message))
            {
                // Redirect to TransactionPage
                Response.Redirect("~/PRL.Trading/TransactionPage.aspx");
            }
            // If thuc hien fail
            else
            {
                // Show pop-up message: message & Reload page
                ClientScript.RegisterStartupScript(this.GetType(), "popup",
                    "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(message) + "');window.location='PostPage.aspx?postID=" + post.ID + "'</script>");
            }
        }

        protected void dgvOrderBuyer_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            BOLTrading bolTrading = new BOLTrading();
            string message = "";
            bool tradingType = false;

            switch (e.CommandName)
            {
                case "AcceptOrder":
                    // Thuc hien accept order
                    tradingType = true;
                    break;

                case "RejectOrder":
                    // Thuc hien reject order
                    tradingType = false;
                    break;
            }

            // Get information of post
            Post post = getPostInfoFromScreen();

            // Get information of order tu order duoc chon
            long orderChoiceID = Convert.ToInt64(dgvOrderBuyer.Rows[index].Cells[6].Text);

            // Perform transaction
            if (!bolTrading.processTransaction(post, orderChoiceID, tradingType, out message))
            {
                // Show pop-up message: message & Reload page
                ClientScript.RegisterStartupScript(this.GetType(), "popup",
                    "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(message) + "');window.location='PostPage.aspx?postID=" + post.ID + "'</script>");
            }
            else
            {
                // Reload page
                Response.Redirect(Request.RawUrl);
            }
        }

        private Post getPostInfoFromScreen()
        {
            Post post = new Post();
            post.ID = Convert.ToInt64(Request.QueryString["postID"]);
            post.UserID = Convert.ToInt64(Session["userID"]);
            post.RiceID = Convert.ToInt32(Session["riceID"]);
            post.Amount = Convert.ToInt64(lblAmount.Text);
            post.TradedAmount = Convert.ToInt64(lblTradedAmount.Text);
            return post;
        }

        protected void dgvOrderBuyer_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton btnAccept = (ImageButton)e.Row.FindControl("btnAccept");
                ImageButton btnReject = (ImageButton)e.Row.FindControl("btnReject");

                btnAccept.ToolTip = rm.GetString("langTooltipAccept");
                btnReject.ToolTip = rm.GetString("langTooltipReject");
                
                e.Row.Cells[9].Text = PRLCommon.ChangeLanguageStatus(e.Row.Cells[9].Text);
            }
        }
    }
}